import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api'
import { setToken, removeToken, setUserInfo, removeUserInfo, getToken, getUserInfo as getStoredUserInfo } from '@/utils/auth'
import type { User, LoginParams } from '@/api/types'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(getToken() || '')
  const userInfo = ref<User | null>(getStoredUserInfo())

  // 登录
  const login = async (loginParams: LoginParams) => {
    try {
      const result:any = await loginApi(loginParams)
      console.log('登录API响应:', result)
      
      // 根据实际API响应结构处理数据
      if (result && result.data.token) {
        token.value = result.data.token
        setToken(result.data.token)
        
        // 登录成功后立即获取用户信息
        try {
          await fetchUserInfo()
        } catch (error) {
          console.error('获取用户信息失败:', error)
          // 如果获取用户信息失败，不影响登录成功的返回
        }

        return { success: true, message: '登录成功' }
      } else {
        return { success: false, message: '登录响应数据格式错误' }
      }
    } catch (error: any) {
      console.error('登录错误:', error)
      return { success: false, message: error.message || '登录失败' }
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const result = await getUserInfoApi()
      userInfo.value = result.data
      setUserInfo(result.data)
      return result
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，清除本地存储的认证信息
      logout()
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('登出API调用失败:', error)
    } finally {
      // 无论API调用是否成功，都清除本地状态
      token.value = ''
      userInfo.value = null
      removeToken()
      removeUserInfo()
    }
  }

  // 检查是否已登录
  const isLoggedIn = computed(() => {
    return !!token.value && !!userInfo.value
  })

  // 检查用户权限
  const hasRole = (role: string) => {
    return userInfo.value?.role === role
  }

  // 检查用户是否有指定权限
  const hasPermission = (permission: string) => {
    if (!userInfo.value?.permissions) return false
    return userInfo.value.permissions.some(p => p.path === permission)
  }

  // 获取用户权限路径列表
  const getUserPermissions = () => {
    return userInfo.value?.permissions?.map(p => p.path) || []
  }

  // 初始化时如果有token但没有用户信息，则获取用户信息
  if (token.value && !userInfo.value) {
    fetchUserInfo().catch(() => {
      // 如果获取失败，清除token
      logout()
    })
  }

  return {
    token,
    userInfo,
    login,
    logout,
    fetchUserInfo,
    isLoggedIn,
    hasRole,
    hasPermission,
    getUserPermissions
  }
})